package no.knowit.pages.ressurs;

import java.util.List;

import no.knowit.entities.Ressurs;

import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Log;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.corelib.components.Zone;
import org.apache.tapestry5.hibernate.annotations.CommitAfter;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

public class NyRessurs {
	@Property
	private Ressurs ressurs;
	@Inject
	private Session session;
	@Property
	private List<Ressurs> ressurser;
	@Property
	private Ressurs tempRessurs;
	@Property
	private boolean tempRessursExists;
	@Component
	private Zone editZone;

	@Log
	void onActivate() {
		onActivate(null);
	}

	public void onActivate(Long id) {
		if (id != null) {
			Criteria criteria = session.createCriteria(Ressurs.class);
			criteria.add(Restrictions.eq("id", id));
			try {
				ressurs = (Ressurs) criteria.list().get(0);
			} catch (Exception e) {
			}
		}
		ressurser = session.createCriteria(Ressurs.class).list();
	}

	public Object onPassivate() {
		try {
			return ressurs.getId();
		} catch (Exception e) {
		}
		return true;
	}

	@Log
	@CommitAfter
	void onSubmitFromNyRessursForm() {
		if (ressurs.getId() != null)
			session.merge(ressurs);
		else
			session.persist(ressurs);
		// Nuller ut denne slik at vi ikke henter opp igjen denne med en gang.
		ressurs = null;
	}

	@Log
	public Zone onActionFromFyllutdata(Long id) {
		Criteria criteria = session.createCriteria(Ressurs.class);
		criteria.add(Restrictions.eq("id", id));
		ressurs = (Ressurs) criteria.list().get(0);
		return editZone;
	}
}
